package com.arvato.common.https;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.common.config_bean.WxMiniproConfig;
import com.arvato.common.ftp.FtpTool;
import com.arvato.common.redis.RedisUtil;
import com.arvato.common.util.ContantFinalUtil;
import com.arvato.common.util.JsonUtil;
/**
 * 
 * @author: smallking
 * 
 * @Descibe:小程序托管平台和微信服务器请求交互的工具类
 * 
 * @Date: 2018年8月2日  下午2:45:31
 */
@Component
public class WxMiniproOwnRequestUtil {
	private Logger logger = LoggerFactory.getLogger(WxMiniproOwnRequestUtil.class);
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Autowired
	private JsonUtil jsonUtil;

	@Autowired
	private FtpTool ftpTool;
	/**
	 * 获取小程序的 access_token
	 * @param appid
	 * @param secret
	 */
	public Result getAccessToken() {
		Result result = new Result(false);
		// 首先从redis里面拿
		String token = redisUtil.get("minipro_access_token" + WxMiniproConfig.APPID);
		if(token != null) {
			result.setResult(true);
			result.setData(token);
			return result;
		}
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxMiniproConfig.APPID + "&secret=" + WxMiniproConfig.SECRET;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取小程序accessToken的返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		if((resultMap.get("errcode") != null) && !"0".equals(resultMap.get("errcode") + "")) {
			result.setData(resultMap);
			return result;
		}
		token = resultMap.get("access_token") + "";
		result.setResult(true);
		result.setData(token);
		redisUtil.set("minipro_access_token" + WxMiniproConfig.APPID, token, 7100);
		return result;
	}	
	
	/**
	 * 获取小程序二维码
	 * @param path 扫码之后的跳转路径
	 * @return
	 */
	public Result getQrcode(String path) {
		Result result = getAccessToken();
		if(result.getCode() == 500) {
			return result;
		}
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("path", path);
			String paramStr = jsonUtil.obj2String(paramMap);
			String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + result.getData();
			InputStream inputStream = HttpsUtil.httpsDownload(url, "POST", paramStr);
			String fileName ="miniqr" + System.currentTimeMillis() + ".png";
			boolean flag = ftpTool.uploadFile(inputStream, fileName);
			if(flag) {
				// 文件上传成功之后 将预览路径给到前台
				logger.info("请求小程序二维码成功,path:" + path);
				result.setData(ContantFinalUtil.IMG_PATH + "?fileName=" + fileName);
			}else {
				logger.info("小程序二维码上传到ftp失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult(false);
			result.setMsg("服务器未知错误。");
		}
		return result;
	}
	/**
	 * 获取小程序的小程序码
	 * @param path
	 * @return
	 */
	public Result getCodePng(String path) {
		Result result = getAccessToken();
		if(result.getCode() == 500) {
			return result;
		}
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("path", path);
			String paramStr = jsonUtil.obj2String(paramMap);
			String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + result.getData();
			InputStream inputStream = HttpsUtil.httpsDownload(url, "POST", paramStr);
			String fileName ="minipng" + System.currentTimeMillis() + ".png";
			boolean flag = ftpTool.uploadFile(inputStream, fileName);
			if(flag) {
				// 文件上传成功之后 将预览路径给到前台
				logger.info("请求小程序小程序码成功,path:" + path);
				result.setData(ContantFinalUtil.IMG_PATH + "?fileName=" + fileName);
			}else {
				logger.info("小程序小程序码上传到ftp失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult(false);
			result.setMsg("服务器未知错误。");
		}
		return result;
	
	}
}
